package org.hong.monkey.network.client;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.hong.monkey.network.buffer.NioManagedBuffer;
import org.hong.monkey.network.protocol.*;
import org.hong.monkey.network.util.NettyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class TransportClient implements Closeable {
    private final Logger logger = LoggerFactory.getLogger(TransportClient.class);

    private final Channel channel;
    private final TransportResponseHandler handler;
    @Nullable
    private String clientId;
    private volatile boolean timedOut;

    public TransportClient(Channel channel, TransportResponseHandler handler) {
        this.channel = Preconditions.checkNotNull(channel);
        this.handler = Preconditions.checkNotNull(handler);
        this.timedOut = false;
    }

    public Channel getChannel() {
        return channel;
    }

    public boolean isActive() {
        return !timedOut && (channel.isOpen() || channel.isActive());
    }

    public SocketAddress getSocketAddress() {
        return channel.remoteAddress();
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String id) {
        Preconditions.checkState(clientId == null, "Client ID has already been set.");
        this.clientId = id;
    }

    public void fetchChunk(
            long streamId,
            final int chunkIndex,
            final ChunkReceivedCallback callback) {
        final String serverAddr = NettyUtils.getRemoteAddress(channel);
        final long startTime = System.currentTimeMillis();
        logger.debug("Sending fetch chunk request {} to {}", chunkIndex, serverAddr);

        final StreamChunkId streamChunkId = new StreamChunkId(streamId, chunkIndex);
        handler.addFetchRequest(streamChunkId, callback);

        channel.writeAndFlush(new ChunkFetchRequest(streamChunkId)).addListener(
                new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            long timeTaken = System.currentTimeMillis() - startTime;
                            logger.trace("Sending request {} to {} took {} ms", streamChunkId, serverAddr,
                                    timeTaken);
                        } else {
                            String errorMsg = String.format("Failed to send request %s to %s: %s", streamChunkId,
                                    serverAddr, future.cause());
                            logger.error(errorMsg, future.cause());
                            handler.removeFetchRequest(streamChunkId);
                            channel.close();
                            try {
                                callback.onFailure(chunkIndex, new IOException(errorMsg, future.cause()));
                            } catch (Exception e) {
                                logger.error("Uncaught exception in RPC response callback handler!", e);
                            }
                        }
                    }
                });
    }

    public void stream(final String streamId, final StreamCallback callback) {
        final String serverAddr = NettyUtils.getRemoteAddress(channel);
        final long startTime = System.currentTimeMillis();
        logger.debug("Sending stream request for {} to {}", streamId, serverAddr);

        synchronized (this) {
            handler.addStreamCallback(callback);
            channel.writeAndFlush(new StreamRequest(streamId)).addListener(
                    new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                long timeTaken = System.currentTimeMillis() - startTime;
                                logger.trace("Sending request for {} to {} took {} ms", streamId, serverAddr,
                                        timeTaken);
                            } else {
                                String errorMsg = String.format("Failed to send request for %s to %s: %s", streamId,
                                        serverAddr, future.cause());
                                logger.error(errorMsg, future.cause());
                                channel.close();
                                try {
                                    callback.onFailure(streamId, new IOException(errorMsg, future.cause()));
                                } catch (Exception e) {
                                    logger.error("Uncaught exception in RPC response callback handler!", e);
                                }
                            }
                        }
                    });
        }
    }

    public long sendRpc(ByteBuffer message, final RpcResponseCallback callback) {
        final String serverAddr = NettyUtils.getRemoteAddress(channel);
        final long startTime = System.currentTimeMillis();
        logger.trace("Sending RPC to {}", serverAddr);

        final long requestId = Math.abs(UUID.randomUUID().getLeastSignificantBits());
        handler.addRpcRequest(requestId, callback);

        channel.writeAndFlush(new RpcRequest(requestId, new NioManagedBuffer(message))).addListener(
                new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            long timeTaken = System.currentTimeMillis() - startTime;
                            logger.trace("Sending request {} to {} took {} ms", requestId, serverAddr, timeTaken);
                        } else {
                            String errorMsg = String.format("Failed to send RPC %s to %s: %s", requestId,
                                    serverAddr, future.cause());
                            logger.error(errorMsg, future.cause());
                            handler.removeRpcRequest(requestId);
                            channel.close();
                            try {
                                callback.onFailure(new IOException(errorMsg, future.cause()));
                            } catch (Exception e) {
                                logger.error("Uncaught exception in RPC response callback handler!", e);
                            }
                        }
                    }
                });

        return requestId;
    }

    /**
     * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to
     * a specified timeout for a response.
     */
    public ByteBuffer sendRpcSync(ByteBuffer message, long timeoutMs) {
        final SettableFuture<ByteBuffer> result = SettableFuture.create();

        sendRpc(message, new RpcResponseCallback() {
            @Override
            public void onSuccess(ByteBuffer response) {
                result.set(response);
            }

            @Override
            public void onFailure(Throwable e) {
                result.setException(e);
            }
        });

        try {
            return result.get(timeoutMs, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw Throwables.propagate(e.getCause());
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }

    public void send(ByteBuffer message) {
        channel.writeAndFlush(new OneWayMessage(new NioManagedBuffer(message)));
    }

    public void removeRpcRequest(long requestId) {
        handler.removeRpcRequest(requestId);
    }

    public void timeOut() {
        this.timedOut = true;
    }

    @VisibleForTesting
    public TransportResponseHandler getHandler() {
        return handler;
    }

    @Override
    public void close() {
        channel.close().awaitUninterruptibly(10, TimeUnit.SECONDS);
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("remoteAdress", channel.remoteAddress())
                .add("clientId", clientId)
                .add("isActive", isActive())
                .toString();
    }
}
